package com.atguigu.tingshu.user.api;

import com.atguigu.tingshu.common.login.RequiresLogin;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.user.service.UserInfoService;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Tag(name = "微信授权登录接口")
@RestController
@RequestMapping("/api/user/wxLogin")
@Slf4j
public class WxLoginApiController {

    private final UserInfoService userInfoService;
    private final RedisTemplate<Object, Object> redisTemplate;


    public WxLoginApiController(UserInfoService userInfoService, RedisTemplate<Object, Object> redisTemplate) {
        this.userInfoService = userInfoService;
        this.redisTemplate = redisTemplate;
    }

    @Operation(summary = "微信小程序授权登录")
    @Parameters({
            @Parameter(name = "code", description = "微信临时凭据", required = true)
    })
    @GetMapping("/wxLogin/{code}")
    public Result<Map<String, String>> wxLogin(@PathVariable String code) {
        Map<String, String> tokenMap = this.userInfoService.wxLogin(code);
        return Result.ok(tokenMap);
    }

    @Operation(summary = "获取登录用户信息")
    @RequiresLogin
    @GetMapping("/getUserInfo")
    public Result<UserInfoVo> getUserInfo() {
        String loginKey = AuthContextHolder.getLoginKey();
        UserInfoVo userInfoVo = (UserInfoVo) this.redisTemplate.opsForValue().get(loginKey);
        return Result.ok(userInfoVo);
    }

    // /api/user/wxLogin/updateUser
    @Operation(summary = "更新当前登录用户信息")
    @Parameters({
            @Parameter(name = "userInfoVo", description = "用户信息Vo对象", required = true)
    })
    @RequiresLogin
    @PostMapping("/updateUser")
    public Result<Void> updateUser(@RequestBody UserInfoVo userInfoVo,
                                   @RequestHeader("token") String token) {
        Long userId = AuthContextHolder.getUserId();
        this.userInfoService.updateUser(userId, userInfoVo, token);
        return Result.ok();
    }
}
